package com.ssm.controllor;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller  
public class UpDownLoad {

	
	@RequestMapping(value = "downFile")  
	public void downPhotoByStudentId(String id, final HttpServletResponse response) throws Exception{  

//	    FileInputStream fmt = new FileInputStream("D://a.xml");
	    FileInputStream fmt = new FileInputStream("D://photo/bankCardPhoto.jpg");
//	    String fileName = "a.xml";  
	    String fileName = "bankCardPhoto.jpg";  
	    fileName = URLEncoder.encode(fileName, "UTF-8");  
	    response.reset();  
	    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
	    response.setContentType("application/octet-stream;charset=UTF-8");  
	    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
	    
	    byte[] bs = new byte[1024];
	    int length = 0 ;
	    while((length=fmt.read(bs))!=-1){
	    	outputStream.write(bs);  
	    }
	    outputStream.flush();  
	    outputStream.close();  
	} 
	
	//文件上传进度条是XMLHttpRequest控制
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(HttpServletRequest request,HttpServletResponse response, @RequestParam("file") MultipartFile file, ModelMap model) throws Exception {
        System.out.println("开始");
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
        // String fileName = new Date().getTime()+".jpg";
        System.out.println(path);
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        // 保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName);
        response.getWriter().print("result");
        return null;
//        return "result";
    }
}
